package com.lzj.server.config;

import com.lzj.server.utils.LogUtils;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author lzj
 * Redisson配置类
 */
@Data
@Configuration
@ConfigurationProperties("spring.data.redisson")
public class RedissonConfig {
    @Value("${spring.data.redisson.host}")
    private String host;
    @Value("${spring.data.redisson.password}")
    private String password;
    @Value("${spring.data.redisson.port}")
    private Integer port;

    private int timeout = 3000;
    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 自动装配
     */
    @Bean
    RedissonClient redissonSingle() {
        Config config = new Config();

        if (!StringUtils.hasLength(host)) {
            throw new RuntimeException("host is  empty");
        }
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(ADDRESS_PREFIX + this.host + ":" + port)
                .setTimeout(this.timeout);
        if (StringUtils.hasLength(this.password)) {
            serverConfig.setPassword(this.password);
        }
        RedissonClient redissonClient = Redisson.create(config);
        LogUtils.init(redissonClient); // 初始化LogUtils
        return redissonClient;
    }
}
